﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
//using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using System.IO.Ports;
using System.Diagnostics;
using Microsoft.Win32;
using ComToKey.Properties;
using ComToKey;
using System.Management;
using System.Collections;
using System.Net.NetworkInformation;

namespace ComToKey
{
    public partial class Form1 : Form
    {
        //启动中标志
        bool start_flag = true;
        //使用4组地址，只有都不通时，才认为网络出问题了
        const int PingAddrCount= 4;
        //初始化时全部重置为true
        bool[] PingStateArray = new bool[PingAddrCount];
        //{ 
        //    true,
        //    true,
        //    true,
        //    true,
        //};

        string[] PingAddrArray = new string[PingAddrCount]
        {
            "www.baidu.com", 
            "www.taobao.com", 
            "www.jd.com",
            "www.apple.com"
        };

        Thread ping_t = null;

        bool WifiResetFlag = false;

        void richtextbox_Upadate(string str)
        {
            Invoke((EventHandler)delegate
            {
                richTextBox1.Text += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + str + "\r\n";
            });
        }

        /// <summary>
        /// 得到指定网卡
        /// </summary>
        /// <param name="networkname">网卡名字</param>
        /// <returns></returns>
        public ManagementObject GetNetWorkByName(string networkname)
        {
            //只要物理网卡
            string netState = "SELECT * From Win32_NetworkAdapter where PhysicalAdapter = TRUE";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == networkname)
                {
                    return manage;
                }
            }

            return null;
        }

        public void NetWorkList(ComboBox cmb_NetWork)
        {
            string manage = "SELECT * From Win32_NetworkAdapter where PhysicalAdapter = TRUE";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
            ManagementObjectCollection collection = searcher.Get();
            List<string> netWorkList = new List<string>();

            foreach (ManagementObject obj in collection)
            {
                netWorkList.Add(obj["Name"].ToString());

            }
            cmb_NetWork.DataSource = netWorkList;


            Console.WriteLine(netWorkList.Count);
        }

        /// <summary>
        /// 禁用网卡
        /// </summary>5
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool DisableNetWork(string networkname)
        {   
            try
            {
                ManagementObject network = GetNetWorkByName(networkname);
                if (network == null)
                {
                    richtextbox_Upadate("无法找到网卡," + networkname);
                    DebugInfoSave.Out_Debug("无法找到网卡," + networkname);
                    return false;
                }

                network.InvokeMethod("Disable", null);
                richtextbox_Upadate("禁用网卡成功," + networkname);
                DebugInfoSave.Out_Debug("禁用网卡成功," + networkname);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 启用网卡
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool EnableNetWork(string networkname)
        {
            try
            {
                ManagementObject network = GetNetWorkByName(networkname);
                if (network == null)
                {
                    richtextbox_Upadate("无法找到网卡," + networkname);
                    DebugInfoSave.Out_Debug("无法找到网卡," + networkname);
                    return false;
                }
                network.InvokeMethod("Enable", null);

                richtextbox_Upadate("使能网卡成功," + networkname);
                DebugInfoSave.Out_Debug("使能网卡成功," + networkname);

                return true;
            }
            catch
            {
                return false;
            }

        }

        public Form1()
        {
            for (int i = 0; i < PingAddrCount; i++ )
            {
                PingStateArray[i] = true;
            }
            InitializeComponent();
            NetWorkList(cmbNetWork);    
        }

        /// <summary>
        /// 重启电脑函数
        /// </summary>
        /// <returns></returns>
        private void resetcompute()
        {
            try
            {
                string para = "/cshutdown -f -r -t 0";
                Process.Start("CMD.exe", para);
            }
            catch (System.Exception)
            {

            }
        }
        /// <summary> 保存用户设置 </summary>
        private void SaveSettings()
        {
            try
            {
                Settings.Default.wifi_name = cmbNetWork.SelectedValue.ToString();
            }
            catch (System.Exception ex)
            {
                DebugInfoSave.Out_Debug(ex.ToString());
            }
            
            Settings.Default.Save();
        }

        /// <summary> 用默认设置初始化窗口控件 </summary>
        private void InitializeControlValues()
        {
            try
            {
                Console.WriteLine(Settings.Default.wifi_name);
                if (cmbNetWork.Items.Contains(Settings.Default.wifi_name))
                {
                    cmbNetWork.Text = Settings.Default.wifi_name;
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
           
        }

        void ping_thread()
        {
            Thread.Sleep(3000);

            while (true)
            {
                Thread.Sleep(1 * 1000);
                for (int i = 0; i < PingAddrCount; i++)
                {
                    PingStateArray[i] = Net_Helper.Ping(PingAddrArray[i]);

                    Console.WriteLine("ping " + PingAddrArray[i] +" " + (PingStateArray[i]?"ok":"error"));
                    richtextbox_Upadate("ping " + PingAddrArray[i] + " " + (PingStateArray[i]?"ok":"error"));

                    if (PingStateArray[i])
                    {
                        Thread.Sleep(5 * 1000);
                        break;
                    }
                    Thread.Sleep(10 * 1000);
                }

                if (WifiResetFlag)
                {                        
                    Invoke((EventHandler)delegate
                    {
                        if (cmbNetWork.Items.Count != 0)
                        {
                            DisableNetWork(cmbNetWork.SelectedValue.ToString());
                            Thread.Sleep(3000);
                            EnableNetWork(cmbNetWork.SelectedValue.ToString());
                            Thread.Sleep(3000);
                        }
                    });

                    WifiResetFlag = false;
                }
           }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //检查是否设置开机启动
            RegistryKey loca_chek = Registry.LocalMachine;
            RegistryKey run_Check = loca_chek.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            string starupPath = Application.ExecutablePath;
            foreach (string com_reg_n in run_Check.GetValueNames())
            {
                if (com_reg_n.Contains("WifiMonitorResetAutoOn"))//是否包含关键字符串
                {
                    if (((string)run_Check.GetValue(com_reg_n)).ToLower() == starupPath.ToLower())
                    {
                        checkBox1.Checked = true;
                        break;
                    }
                    else
                    {
                        checkBox1.Checked = false;
                    }
                }
            }


            // 存储用户设置
            InitializeControlValues();

            loca_chek.Close();
            start_flag = false;

            //启动时最小化到窗口  

            ping_t = new Thread(ping_thread);
            ping_t.IsBackground = true;
            ping_t.Start();
        }

        //添加（重写）窗口尺寸变动函数Form1_Resize
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)    //最小化到系统托盘
            {
                notifyIcon1.Visible = true;    //显示托盘图标
                this.Hide();    //隐藏窗口
            }
        }
       

        //添加双击托盘图标事件（双击显示窗口）
        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            notifyIcon1.Visible = false;
            this.Show();
            WindowState = FormWindowState.Normal;
            this.Focus();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //注意判断关闭事件Reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //e.Cancel = true;    //取消"关闭窗口"事件
                //this.WindowState = FormWindowState.Minimized;    //使关闭时窗口向右下角缩小的效果
                //notifyIcon1.Visible = true;
                //this.Hide();
                //return;
            }
            SaveSettings();
            Environment.Exit(0);
        }

        /// <summary>
        /// 隐藏窗口点击选项判断函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Text)
            {
                case "开机启动":
                    AutoRun(true);
                    break;
                case "关闭电脑":
                    shutdownpower();
                    break;
                case "显示窗口":
                    notifyIcon1_DoubleClick(sender, e);
                    break;
                case "退出":
                    try
                    {

                    }
                    catch (System.Exception)
                    {

                    }  
                    Application.Exit();
                    break;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            toolStripStatusLabel2.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
        }


        private void label6_DoubleClick(object sender, EventArgs e)
        {
           
        }

        /// <summary>
        /// 关机函数
        /// </summary>
        /// <returns></returns>
        private void shutdownpower()
        {
            try
            {
                string para = "/cshutdown -f -s -t 0";
                Process.Start("CMD.exe", para);
            }
            catch (System.Exception)
            {

            }
        }
        /// <summary>
        /// 设置开机自动启动函数
        /// </summary>
        /// <param name="IsAutoRun"></param>
        /// <returns></returns>
        private bool AutoRun(bool IsAutoRun)
        {
            string reg_com = "WifiMonitorResetAutoOn";
            bool isexistflag = false;

            //获取程序执行路径..
            string starupPath = Application.ExecutablePath;
            //class Micosoft.Win32.RegistryKey. 表示Window注册表中项级节点,此类是注册表装.
            RegistryKey local = Registry.LocalMachine;
            RegistryKey run = local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
            
            try
            {
                 //SetValue:存储值的名称
                if (IsAutoRun == false)
                {
                    foreach (string com_reg_n in run.GetValueNames())
                    {
                        if (com_reg_n.Contains("WifiMonitorResetAutoOn"))//是否包含关键字符串
                        {
                            if (((string)run.GetValue(com_reg_n)).ToLower() == starupPath.ToLower())
                            {
                                isexistflag = true;
                                reg_com = com_reg_n;
                                break;
                            }
                        }
                    }
                    if (isexistflag)
                    {
                        run.DeleteValue(reg_com);//取消开机运行
                    }
                    else
                    {
                        return true;
                    }
                    //MessageBox.Show("取消开机启动！");
                }
                else
                {
                    int num = 0;
                    //在设置开机启动时，查找"WifiMonitorResetAutoOn"最大序号，写入
                    foreach (string com_reg_n in run.GetValueNames())
                    {
                        if (com_reg_n.Contains("WifiMonitorResetAutoOn"))//是否包含关键字符串
                        {
                            try
                            {
                                int tmp = Int32.Parse(com_reg_n.Remove(0, 8));
                                
                                if (tmp > num)
                                {
                                    num = tmp;
                                } 
                            }
                            catch (System.Exception)
                            {
                            	
                            }
                            
                        }
                    }
                    num += 1;
                    reg_com = "WifiMonitorResetAutoOn" + num.ToString();
                    run.SetValue(reg_com, starupPath);//设置开机运行
                    //MessageBox.Show("开机启动！");
                }
                local.Close();
                return true;
            }
            catch
            {
                MessageBox.Show("开机启动设置失败！");
                local.Close();
                return false;
            }
        }
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (start_flag)
            {
                return;
            }
            if (checkBox1.Checked)//选中表示自动运行
            {
                AutoRun(true);                
            }
            else
            {
                AutoRun(false);
            }
        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            if (!start_flag)
            {
                timer3.Enabled = false;
                this.WindowState = FormWindowState.Minimized;
            }
        }

        UInt32 run_time = 0;
        UInt32 run_time_lost = 0;
        private void timer2_Tick(object sender, EventArgs e)
        {
            run_time++;
            bool find_flag = false;

            for (int i = 0; i < PingAddrCount; i++ )
            {
                if (PingStateArray[i])
                {
                    //只要有一个true即可
                    find_flag = true;
                    break;
                }
            }

            if (find_flag == false && run_time_lost == 0)
            {
                //假如没找到 记录下当前试驾
                run_time_lost = run_time;
            }
            else if (find_flag == true)
            {
                run_time_lost = 0;
            }

            //无网络超过多少时间 重置网卡 5分钟
            if (find_flag == false && run_time - run_time_lost > 5 * 60 && WifiResetFlag == false)
            {
                WifiResetFlag = true;
                richtextbox_Upadate("系统将重置网卡...");
                DebugInfoSave.Out_Debug("系统将重置网卡...");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            NetWorkList(cmbNetWork);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                ping_t.Abort();

                Application.Exit();
            }
            catch (System.Exception)
            {

            }
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.SelectionLength = 0;
            richTextBox1.Focus();

            //大于500k 清除一下
            if (richTextBox1.Text.Length > 100 * 1024)
            {
                richTextBox1.Text = "";
            }
        }
   }
}
